import { getAction } from '@api/manage'
import CommonApi from '@api/Common'

export const AddressChangeMixin = {
  data() {
    return {
      addressOptions: [],
    }
  },
  created() {

  },
  methods: {
    onAddressSelected(e, item) {
      this.$forceUpdate()
      this.form.address = item.filter(item => item.label).map(item => item.label).join(' / ')
      this.form.addressList = this.form.addressCollect.join(",")
    },

    async renderAddressAtMounted(){
      // 网点区域
      this.form.addressCollect = (this.form.addressList || '').split(',')
      if (this.form.addressCollect && this.form.addressCollect.length > 0) {
        const dataProvince = this.addressOptions.filter(item => {
          return item.value === this.form.addressCollect[0].trim()
        })
        if (dataProvince.length) {
          await this.loadAddressOnChange(dataProvince)
          const dataCity = dataProvince[0].children.filter(item => {
            return item.value === this.form.addressCollect[1].trim()
          })
          if (dataCity.length) {
            await this.loadAddressOnChange(dataCity)
            const dataArea = dataCity[0].children.filter(item => {
              return item.value === this.form.addressCollect[2].trim()
            })
          }
        }
      }
    },

    async loadAddressForCascader() {
      await getAction(CommonApi.addressList, {}).then(res => {
          this.addressOptions = res.result.map(item => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: false
            }
          })

      })
    },

    async loadAddressOnChange(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true
      let data = {}
      let isLeaf = false
      // load options lazily
      if (targetOption.value.length === 2) {
        // 请求市
        data = { provinceCode: targetOption.value }
      } else if (targetOption.value.length === 4) {
        // 请求区
        data = { cityCode: targetOption.value }
        isLeaf = true
      }
      await getAction(CommonApi.addressList, data).then(res => {
        targetOption.children = res.result.map(item => {
          return {
            label: item.name,
            value: item.code,
            isLeaf
          }
        })
      })
      targetOption.loading = false
      this.addressOptions = [...this.addressOptions]
    },
  }
}

